package com.ronghui.cash.util;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/5 0005.
 */
public class HttpPostUtil {


    /**
     * post 请求 url，请求参数为 json，传入参数为 Map<String, Object>
     * @param url
     * @param map
     * @return
     */
    public static String HttpPostWithJson(String url, Map<String, Object> map) {
        String json = MapToJsonstr(map);
        String returnValue = "这是默认返回值，接口调用失败";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try{
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();

            //第二步：创建httpPost对象
            org.apache.http.client.methods.HttpPost httpPost = new org.apache.http.client.methods.HttpPost(url);

            //第三步：给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);

            //第四步：发送HttpPost请求，获取返回值
            //HttpResponse  returnValuee = httpClient.execute(httpPost); //调接口获取返回值时，必须用此方法

            CloseableHttpResponse httpResonse = httpClient.execute(httpPost);
            int statusCode = httpResonse.getStatusLine().getStatusCode();
            if(statusCode == 200)
            {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResonse.getEntity().getContent()));
                String line;
                StringBuffer jsonString = new StringBuffer();
                while((line = bufferedReader.readLine()) != null) {
                    jsonString.append(line);
                }
                returnValue = jsonString.toString();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //第五步：处理返回值
        return returnValue;
    }

    //把map对象转成json格式的String字符串
    private static String  MapToJsonstr(Map<String, Object> map){
        //System.out.println("++++++++++++++++++转json之前的map对象：" + map.toString());
        ObjectMapper json = new ObjectMapper();
        String params = null;
        try {
            //把map对象转成json格式的String字符串
            params = json.writeValueAsString(map);
            //System.out.println("++++++++++++++++++转成的json格式字符串：" + params);
        } catch (JsonGenerationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return params;
    }
}
